import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

///dialog
class DialogDemo extends StatefulWidget {
  const DialogDemo({Key? key}) : super(key: key);

  @override
  _DialogDemoState createState() => _DialogDemoState();
}

class _DialogDemoState extends State<DialogDemo> {
  List<int> _list = [];

  @override
  void initState() {
    for (int i = 0; i < 5; i++) {
      _list.add(i);
    }
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("dialog"),
      ),
      body: Column(
        children: <Widget>[
          ElevatedButton(
            onPressed: () {
              _showAlert();
            },
            child: Text("Alert Dialog"),
          ),
          ElevatedButton(
            onPressed: () {
              _showListDialog();
            },
            child: Text("Simple Dialog"),
          )
        ],
      ),
    );
  }

  ///显示AlertDialog
  ///1.showDialog
  ///2.CupertinoAlertDialog
  ///3. Navigator.pop(context,true);返回
  ///4.barrierDismissible 点击外面不关闭
  void _showAlert() async {
    var result = await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            // return CupertinoAlertDialog(
            title: Text("title"),
            content: Text("内容"),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                  child: Text("确定")),
              TextButton(
                  onPressed: () {
                    Navigator.pop(context, false);
                  },
                  child: Text("取消")),
            ],
          );
        });
    print("$result");
  }

  void _showListDialog() async {
    var result = await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return SimpleDialog(
            elevation: 4,
            title: Center(child: Text("title")),
            children: _list
                .map((e) => GestureDetector(
                      child: Center(child: Text("关闭 $e")),
                      onTap: () {
                        Navigator.pop(context, e.toString());
                      },
                    ))
                .toList(),
          );
        });
    print("$result");
  }
}
